import os
from configparser import ConfigParser, NoSectionError, NoOptionError

from loguru import logger

from settings.constant import p_path


class ConfigUtil:
    """读取配置文件类"""
    def __init__(self, filename):
        self.filename = filename
        config = ConfigParser()
        config.read(filename, encoding='utf-8')
        self.config = config

    def read(self, section, option):
        """读取配置文件"""
        try:
            logger.info(f"读取到配置文件的【{section}】中的option是【{option}】的数据是【{self.config.get(section, option)}】")
            return self.config.get(section, option)
        except NoSectionError:
            logger.error(f"未找到{section}这个section------")
            # print(f"未找到{section}这个section------")
        except NoOptionError:
            logger.error(f"未找到{option}这个option-------")
            # print(f"未找到{option}这个option-------")

    def write(self, section, option, value):
        """配置文件写入操作"""
        if self.config.has_option(section):
            self.section.set(section, option, value)
            with open(self.filename, 'w', encoding='utf-8') as f:
                self.config.write(f)

    def get_list(self, section, option):
        option_str = self.read(section, option)
        if isinstance(eval(option_str), list):
            return eval(option_str)
        return None


config = ConfigUtil(os.path.join(p_path.CONFIG_PATH, 'config.ini'))

if __name__ == '__main__':
    print(config.read('logger', 'name'))
